package com.findfuture.common.interceptor;

import com.findfuture.common.util.Constants;
import com.findfuture.common.util.CookieUtil;
import com.findfuture.demo.model.Users;
import com.findfuture.demo.service.IUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyHandlerInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private IUsersService usersService;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        //就简单判断了一下，如果要详细控制可以用spring security
        String url = request.getRequestURI();
        if (url.endsWith("login") || url.endsWith("uploadImage") || url.startsWith("/index"))
            return true;
        Cookie cookie = CookieUtil.getCookieByName(request, "user");
        if (cookie != null) {
            String[] value = cookie.getValue().split("=");
            Users users = usersService.getUserByName(value[0]);

            if (users != null && users.getPassword().equals(value[1])) {
                request.getSession().setAttribute(Constants.USER_INFO_SESSION, users);
            }
        }
        if (request.getSession() != null && request.getSession().getAttribute(Constants.USER_INFO_SESSION) != null) {
            Users users = (Users) request.getSession().getAttribute(Constants.USER_INFO_SESSION);
            //如果是普通用户，只能查看线下用户页面！
            if (users.getState() == 0) {
                if (!url.endsWith("/stat/" + users.getId()) && !url.endsWith("logout"))
                    response.sendRedirect(request.getContextPath() + "/user/stat/" + users.getId());
            }
            return true;
        }

        response.sendRedirect(request.getContextPath() + "/login.jsp");
        return false;

    }

}
